package com.flw.dao.impl;

import com.flw.dao.IUserDao;
import com.flw.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * 本类用于:
 *
 * @author Bruce
 * @create 2017-07-20 14:35
 **/
@SuppressWarnings("all")
@Repository
@Transactional
public class UserDaoImpl implements IUserDao{

    //获取SessionFactory
    @Autowired
    private SessionFactory sessionFactory;

    //获取Session
    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    public void save(User user) {
        getSession().save(user);
    }

    public List<User> findAll() {
        return getSession().createQuery("from User").list();
    }

    public User findByUserNum(String userNum) {
        return (User) getSession().createQuery("from User where userNum=:uNum").setParameter("uNum",userNum).uniqueResult();
    }

    public User update(User user) {
        User u = (User) getSession().get(User.class,user.getId());
        if(u != null){
            //因为查询了该用户两次，所以Session必须要清理一下，不然可能会导致Session中存在两个User
            getSession().clear();
            getSession().update(user);
        }
        return null;
    }

    public void delById(Long id) {
        User u = (User) getSession().get(User.class,id);
        if(u != null){
            getSession().delete(u);
        }
    }

    @Override
    public User findByPhone(String phone) {
        return (User) getSession().createQuery("from User where phone=:uphone").setParameter("uphone",phone).uniqueResult();
    }


}
